/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.failover;

import org.retabel.persistence.dao.failover.FailureObjectDao;
import org.retabel.persistence.entity.failover.FailureObject;
import org.retabel.service.render.RenderAsyncService;
import org.retabel.service.render.RenderParameter;
import org.retabel.service.render.RenderServiceBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.io.*;
import java.util.List;

/**
 * Class description.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 23:06 21.09.11
 *
 * @author Burt Parkers
 * @version 1.0
 */
@Stateless
public class FailoverServiceBean implements FailoverService {

    /** The Logger. */
    private static final Logger logger = LoggerFactory.getLogger(RenderServiceBean.class);

    /** Dao to access the failure object table. */
    @EJB
    private FailureObjectDao failureObjectDao;

    /** Async Renderservice. */
    @EJB
    private RenderAsyncService renderAsyncService;

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void failover(Failable failable, String className) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try(ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(failable);
            FailureObject failureObject = new FailureObject();
            failureObject.setClassName(className);
            failureObject.setSerializedData(bos.toByteArray());
            failureObjectDao.create(failureObject);
        } catch (IOException e) {
            logger.error("Error during failover procedure, failover data lost.");
            throw new RuntimeException(e);
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void redo(int id) {
        FailureObject failureObject = failureObjectDao.find(id);
        if (failureObject == null) throw new RuntimeException("Failure Object " + id + " not found!");
        redo(failureObject);
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void redo() {
        List<FailureObject> all = failureObjectDao.findAll();
        for (FailureObject failureObject : all) {
            redo(failureObject);
        }
    }

    /**
     * Redos a specific failure object.
     *
     * @param failureObject the object to redo.
     */
    private void redo(FailureObject failureObject) {
        byte[] serializedData = failureObject.getSerializedData();
        ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
        try (ObjectInput in = new ObjectInputStream(bis)) {
            String className = failureObject.getClassName();
            Object failable = in.readObject();
            if (className.equals(RenderAsyncService.class.getName())) {
                renderAsyncService.render((RenderParameter) failable);
            }
        } catch (IOException e) {
            logger.error("Error during failover procedure, failover cannot be read.");
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
